package com.lvhx.springboot.sofarpc;

import com.lvhx.facade.RunJobService;
import com.lvhx.facade.dto.RunJobRequest;
import com.lvhx.facade.dto.RunJobResponse;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.Date;

public class RunJobServiceImpl implements RunJobService {
    @Autowired
    private JobLauncher jobLauncher;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private JobRegistry jobRegistry;

    @Override
    public RunJobResponse runJob(RunJobRequest request) {
        Job job = (Job) applicationContext.getBean(request.getJobName());

        try {
            Job newjob = jobRegistry.getJob(request.getJobName());
            jobLauncher.run(newjob
                    ,new JobParametersBuilder()
                    .addDate("currentDate",new Date())
                    .addString("username","xiaobu")
                    .addDate("PostDate",request.getPostDate())
                    .toJobParameters());
        } catch (JobExecutionAlreadyRunningException e) {
            e.printStackTrace();
        } catch (JobRestartException e) {
            e.printStackTrace();
        } catch (JobInstanceAlreadyCompleteException e) {
            e.printStackTrace();
        } catch (JobParametersInvalidException e) {
            e.printStackTrace();
        }catch (NoSuchJobException e){
            e.printStackTrace();
        }
        RunJobResponse response = new RunJobResponse();
        response.setMessage("run job success ");
        return response;
    }
}
